<?php

namespace app\admin\model;

use app\lib\Qiniu;

//use app\admin\model\Image;
//use think\Model;

class Product extends Base
{

    // 数据表名称
    //protected $table;

    // 当前模型名称 不带前缀
    protected $name = 'product';

    // 数据表主键 复合主键使用数组定义 不设置则自动获取
    protected $pk = 'id';

    // 字段验证规则
    //protected $validate = true;


    public static function _after_delete($id)
    {
        if (is_array($id)) {
            $list = Image::where('related_table', 'product')->whereIn('related_id', $id)->select();
        } else {
            $list = Image::where('related_table', 'product')->where('related_id', $id)->select();
        }

        $Qiniu = new Qiniu();
        foreach ((array)$list as $v) {
            $key = substr(strrchr($v['img_url'], '/'), 1);
            // 删除七牛图片
            $res = $Qiniu->delImg($key);

            Image::where('id', $v['id'])->delete();
        }
    }

    /**
     * 处理商品格式
     */
    public function formatProducts($products)
    {
        if ($products) {
            $unitArr = get_product_unit();
            foreach ($products as &$item) {
                $item['unit'] = $unitArr[$item['unit']];
                // 库存
                //if (!isset($item['qty'])) {
                    $item['qty'] = $this->getStock($item['id']);
                //}

                $productId = $item['id'];
                // 活动商品不在普通商品区显示，但是有可能活动商品到期了，但是type没有改变
                if ($item['type'] == 1) {
                    // 是否是活动商品 - 限时特价活动
                    // 当前小时
                    $nowHour = date('G');
                    if ($nowHour >= 7 && $nowHour < 10) {
                        $time_range = 7;
                    } elseif ($nowHour >= 10 && $nowHour < 13) {
                        $time_range = 10;
                    } elseif ($nowHour >= 13 && $nowHour < 16) {
                        $time_range = 13;
                    } elseif ($nowHour >= 16 && $nowHour < 19) {
                        $time_range = 16;
                    } elseif ($nowHour >= 19 && $nowHour < 21) {
                        $time_range = 19;
                    } else {
                        $time_range = '';
                    }
                    if ($time_range) {
                        $flashsaleWhere = [
                            'product_id' => $productId,
                            'status' => 1,
                            'start_time' => ['elt', date('Y-m-d H:i:s')],
                            'end_time' => ['egt', date('Y-m-d H:i:s')],
                        ];
                        $flashsaleWhere['effective_date'] = ['like', '%,' . $time_range . ',%'];
                        $flashsaleInfo = Flashsale::where($flashsaleWhere)->field('promotion_type, promotion_discount, markup, buy_limit_type, buy_limit_num, start_time, end_time, effective_date, to_user_type, to_users, range, store_ids')->find();
                        if ($flashsaleInfo) {
                            $item['is_flashsale'] = 1; // 限时特价商品
                            $item['promotion_type'] = $flashsaleInfo['promotion_type'];
                            $item['promotion_discount'] = $flashsaleInfo['promotion_discount'];
                            $item['buy_limit_type'] = $flashsaleInfo['buy_limit_type'];
                            $item['buy_limit_num'] = $flashsaleInfo['buy_limit_num'];
                            // 原价
                            $item['ori_price'] = $item['price'];
                            // 优惠后的价格
                            $item['price'] = $flashsaleInfo['markup'];
                            // 限购数
                            if ($flashsaleInfo['buy_limit_type'] == 1) {
                                $item['limit_num'] = 1;
                            } elseif ($flashsaleInfo['buy_limit_type'] == 2) {
                                $item['limit_num'] = 0;
                            } else {
                                $item['limit_num'] = $flashsaleInfo['buy_limit_num'];
                            }

//                            $item['start_time'] = $flashsaleInfo['start_time'];
//                            $item['end_time'] = $flashsaleInfo['end_time'];
//                            $item['to_user_type'] = $flashsaleInfo['to_user_type'];
//                            $item['to_users'] = $flashsaleInfo['to_users'];
//                            $item['to_users'] && $item['to_users'] = explode(',', $item['to_users']);

                            // 结束时间的时间戳
                            $endTime = strtotime(date('Y-m-d') . ' ' . ($time_range + 2) . ':59:59');
                            $item['endTime'] = $endTime;
                        } else {
                            $item['type'] = 0;
                        }
                    } else {
                        $item['type'] = 0;
                    }
                } elseif ($item['type'] == 2) {
                    // 是否是活动商品 - 买赠活动
                    $buygiftInfo = Buygifts::where(['buy_product_id' => $productId, 'status' => 1])->field('gift_product_id, buy_num, gift_num, to_user_type, to_users, range, store_ids')->find();
                    if ($buygiftInfo) {
                        $item['gift_product_id'] = $buygiftInfo['gift_product_id'];
                        $item['buy_num'] = $buygiftInfo['buy_num'];
                        $item['gift_num'] = $buygiftInfo['gift_num'];
                        $item['to_user_type'] = $buygiftInfo['to_user_type'];
                        $item['to_users'] = $buygiftInfo['to_users'];
                        $item['to_users'] && $item['to_users'] = explode(',', $item['to_users']);
                        // 赠送商品
                        $item['gift_product_info'] = Product::where('id', $item['gift_product_id'])->field('name, price, unit')->find();
                        $item['gift_product_info']['unit'] = $unitArr[$item['gift_product_info']['unit']];
                    } else {
                        $item['type'] = 0;
                    }
                } elseif ($item['type'] == 3) {
                    // 是否是活动商品 - 加价换购
                    // 限购数量
                    $repurchaseInfo = Repurchase::where(['product_id' => $productId, 'status' => 1])->field('markup, limit_num')->find();
                    if ($repurchaseInfo) {
                        $item['price'] = $repurchaseInfo['markup']; // 换购价
                        $item['limit_num'] = $repurchaseInfo['limit_num'];
                    }
                } else {
                    // 是否是拼团商品
                    $groupproductInfo = Groupproduct::where(['product_id' => $productId, 'status' => 1, 'start_time' => ['elt', time()], 'end_time' => ['egt', time()]])->field('group_price, group_succ_count, group_succ_time, confine_count')->find();
                    if ($groupproductInfo) {
                        $item['group_price'] = $groupproductInfo['group_price'];
                        $item['group_succ_count'] = $groupproductInfo['group_succ_count'];
                        $item['group_succ_time'] = $groupproductInfo['group_succ_time'];
                        $item['confine_count'] = $groupproductInfo['confine_count'];
                        $item['type'] = 4;
                    }
                }
            }
        }

        return $products;
    }

    /**
     * 获取库存
     */
    public static function getStock($id)
    {
        $stock_num = 0;
        $stock = Stock::where('product_id', $id)->find();
        if ($stock) {
            $stock_num = $stock->marketable;
        }

        return $stock_num;
    }
}